﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;

public class ParseFeedItemProcedure
{

    [Serializable]
    [SqlUserDefinedType(Format.Native)]
    public class WordFriquency
        : INullable
    {
        public int Friquency { get; set; }
        public string Word { get; set; }
        public WordFriquency(string word, int friquency)
        {
            Word = word;
            Friquency = friquency;
        }

        public bool IsNull
        {
            get { return Word == null; }
        }
    }

    [SqlProcedure]
    public static void ParseFeedItem(SqlString feedItemText)
    {
        if(feedItemText.IsNull)
            return;
        using(var connection = new SqlConnection("context connection=tru"))
        {
            var words = GetWords(feedItemText.Value);
        }
    }
    [SqlFunction(TableDefinition = "word NVARCHAR(1000), frequency Int", FillRowMethodName = "FillRow")]
    public static IEnumerable GetWords(string feedItemText)
    {
        if (string.IsNullOrEmpty(feedItemText))
            return new Dictionary<string, int>();

        var words = new Dictionary<string, int>(feedItemText.Length / 4);
        var firstLatter = 0;
        bool tagOpened = false;
        for (var currentLatter = 0; currentLatter <= feedItemText.Length; currentLatter++)
        {
            if (currentLatter < feedItemText.Length && char.IsLetter(feedItemText[currentLatter]))
                continue;

            if (currentLatter > firstLatter && !tagOpened)
            {
                var word = feedItemText.Substring(firstLatter, currentLatter - firstLatter).ToUpper();
                if (words.ContainsKey(word))
                    words[word]++;
                else
                    words.Add(word, 1);
            }
            firstLatter = currentLatter + 1;

            if (currentLatter < feedItemText.Length)
            {
                tagOpened = tagOpened
                                ? feedItemText[currentLatter] != '>'
                                : feedItemText[currentLatter] == '<';
            }

        }
        return words;
    }
    public static void FillRow(object obj, out string word, out int frequency)
    {
        word = ((KeyValuePair<string, int>)obj).Key;
        frequency = ((KeyValuePair<string, int>)obj).Value;
    }
};
